import clone from '@feidao/web/atom/core/obj/clone';
import { generate as generate_url } from '@feidao/core/querystring';
import format from '@feidao/web/atom/core/dt/format';
import { Params } from './params2query';

//! this function could just be used in this project
const time2str = ['confirm_date', 'effectivedate', 'enddate', 'log_date', 'publication_date', 'block_date', 'valitydate', 'date_of_issue', 'start_time', 'finish_time', 'plan_time', 'staff_hiredate', 'docking_date', 'auditdate'];
export default function generate(location: string, params: Params, name2title: { [field: string]: string; }) {
	if (!params.param) {
		params.param = {};
	}
	if (!params.order) {
		params.order = {};
	}
	const tmp1 = ((param) => {
		const fields = Object.keys(param);
		return fields.map((field) => {
			const field_title = name2title[field];
			const v = param[field];
			const field_value = (() => {
				if (time2str.indexOf(field) >= 0 && Array.isArray(v)) {
					if (v.length === 2) {
						if (v[0]) {
							return `从${format(v[0], 0)}至${format(v[1], 0)}`;
						} else {
							return `至${format(v[1], 0)}结束`;
						}
					} else if (v.length === 1) {
						return `从${format(v[0], 0)}开始`;
					}
				} else if (time2str.indexOf(field) >= 0 && v === 0) {
					return '空';
				} else if (v === true) {
					return '是';
				} else if (v === false) {
					return '否';
				} else if (v === '') {
					return '空';
				} else {
					return v.toString() as string;
				}
			})();
			const tmp = clone(params);
			delete tmp.param[field];
			const url = generate_url(tmp, location);
			return {
				type: 1,
				field_title,
				field_value,
				url
			};
		});
	})(params.param);
	const tmp2 = ((order) => {
		const fields = Object.keys(order);
		return fields.map((field) => {
			const field_title = name2title[field];
			const v = order[field];
			const field_value = (() => {
				switch (v) {
					case undefined:
					case null:
					case true:
					case 'true':
					case 'TRUE':
					case 'True':
						return 'asc';
					default:
						return 'desc';
				}
			})();
			const tmp = clone(params);
			delete tmp.order[field];
			const url = generate_url(tmp, location);
			return {
				type: 2,
				field_title,
				field_value,
				url
			};
		});
	})(params.order);
	return tmp1.concat(tmp2);
}
